package com.million.project.controller;

import com.million.project.utils.*;
import com.million.project.pojo.IsCode;
import com.million.project.pojo.Users;
import com.million.project.service.UserService;

import java.util.HashMap;
import java.util.Map;
import java.util.Random;
import java.util.concurrent.TimeUnit;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import static com.million.project.utils.RedisConstants.*;
import static com.million.project.utils.RedisConstants.LOGIN_CODE_TTL;

@RestController
@RequestMapping("/login")
public class UserController {
    @Autowired
    private UserService userService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/test")
    public String test(){
        return "login测试成功！";
    }

    /**
     * 用账号密码登录,登陆成功后将username存入session中
     *
     * @param users
     * @return
     */
    @PostMapping
    public Result loginByPassword(@RequestBody Users users, HttpSession session) {
//        users.setPassword(PasswordEncoder.encode(users.getPassword()));
        System.out.println(users.getPassword());
        Users newUser = userService.LoginByPassword(users.getUsername(), users.getPassword());
        System.out.println(newUser);
        Result result = new Result();
        if (newUser != null) {
            result.setCode("1");
            result.setData(newUser);
            result.setMessage("成功登录，请查看用户信息！");
            // 登陆成功就将username存入session
            session.setAttribute("username", users.getUsername());
        } else {
            result.setCode("0");
            result.setData(null);
            result.setMessage("登录失败，请正确输入账号与密码！");
        }
        return result;
    }

    /**
     * 得到验证码
     * 注册的时候得到验证码
     *
     * @param users
     * @param request
     * @return
     */

    @PostMapping("/getRegisterCode")
    public Result getCode(@RequestBody Users users, HttpServletRequest request) throws Exception {
        Result result = new Result();
        if (userService.SelectByUsername(users.getUsername()) == null) {
            HttpSession session = request.getSession();
            String code = "";
            Random random = new Random();
            code += (random.nextInt(900000) + 100000); //100000-999999
            session.setAttribute("username", users.getUsername());
            // 存入redis中  并且设置有效时间为15分钟
            redisTemplate.opsForValue().set(Regis_CODE_KEY + users.getUsername(), code
                , Regis_CODE_TTL, TimeUnit.MINUTES);
            /*session.setAttribute("code", s);
            session.setMaxInactiveInterval(30 * 60); //30分钟有效期*/
            //上线再使用
            SMS.sendMessage(users.getUsername(),code);
            result.setCode("1");
            result.setMessage("验证码已发送！");
            System.out.println(code);
        } else {
            result.setCode("0");
            result.setMessage("该手机号已被注册");
            System.out.println("该手机号已被注册");
        }
        return result;
    }

    /**
     * 得到验证码
     * 该验证码用于得到验证码拿来登录
     *
     * @param users
     * @param request
     * @return
     */
    @PostMapping("/getlogincode")
    public Result getLoginCode(@RequestBody Users users, HttpServletRequest request)
            throws Exception {
        Result result = new Result();
        if (userService.SelectByUsername(users.getUsername()) != null) {
            HttpSession session = request.getSession();
            String code = "";
            Random random = new Random();
            code += (random.nextInt(900000) + 100000); //100000-999999
            session.setAttribute("username", users.getUsername());
            // 存入redis ，并且设置有效时间为15分钟
            redisTemplate.opsForValue().set(LOGIN_CODE_KEY + users.getUsername(),
                code, LOGIN_CODE_TTL, TimeUnit.MINUTES);
            /* session.setAttribute("code", s);*/
            session.setMaxInactiveInterval(30 * 60);//30分钟有效期
            //上线再使用
            SMS.sendMessage(users.getUsername(),code);
            result.setCode("1");
            result.setMessage("验证码已发送！");
            System.out.println(code);
        } else {
            result.setCode("0");
            result.setMessage("没有该手机号");
            System.out.println("没有该手机号");
        }
        return result;
    }

    /**
     * 验证码登录
     */
    @PostMapping("/loginCode")
    public Result loginCode(@RequestBody IsCode iscode, HttpServletRequest request) {
        Result result = new Result();

        HttpSession session = request.getSession();

        /* String s = (String) session.getAttribute("code");*/

        /*String username = (String) session.getAttribute("username");*/
        String username = iscode.getUsername();

        // 从redis中拿出验证码
        String code = redisTemplate.opsForValue().get(LOGIN_CODE_KEY + username);
        System.out.println("redis拿出的验证码为："+code);

        if (code != null && iscode != null) {
            if (code.equals(iscode.getCode()) && code != null && code != "" && username.equals(username)) {
                result.setData(userService.SelectByUsername(username));
                result.setCode("1");
                result.setMessage("验证成功，开始下一步");
                System.out.println(1123);
            } else {
                result.setCode("0");
                result.setMessage("验证失败，请输入正确验证码");
            }
        } else {
            result.setCode("0");
            result.setMessage("验证失败，请输入正确验证码");
        }
        return result;
    }

    /**
     * 判断验证码是否正确
     *
     * @param iscode
     * @param request
     * @return
     */
    @PostMapping("/isCode")
    public Result isCode(@RequestBody IsCode iscode, HttpServletRequest request) {
        Result result = new Result();
        HttpSession session = request.getSession();
       /* String s = (String) session.getAttribute("code");
        String username = (String) session.getAttribute("username");*/
        String username = iscode.getUsername();

        // 从redis中拿出验证码
        String code = redisTemplate.opsForValue().get(Regis_CODE_KEY + username);
        System.out.println("redis拿出的验证码为："+code);
        if (code != null && iscode != null) {
            if (code.equals(iscode.getCode()) && code != null && code != "" && username.equals(iscode.getUsername())) {
                result.setCode("1");
                result.setMessage("验证成功，开始下一步");
                System.out.println(1123);
            } else {
                result.setCode("0");
                result.setMessage("验证失败，请输入正确验证码");
            }
        } else {
            result.setCode("0");
            result.setMessage("验证失败，请输入正确验证码");
        }
        return result;
    }

    /**
     * 注册一个新用户
     */
    @PostMapping("/save")
    public Result save(@RequestBody Users users, HttpServletRequest request) {
        HttpSession session = request.getSession();
//    String username= (String) session.getAttribute("username");
        if (userService.Register(users.getUsername(), users.getPassword(), "司机") == 0) {
            Result result = new Result();
            result.setMessage("注册失败");
            result.setCode("0");
            return result;
        }
        System.out.println(123);
        Users newUser = new Users();
        newUser.setUsername(users.getUsername());
        newUser.setPassword(users.getPassword());
        Result result = new Result();
        result.setMessage("注册成功");
        result.setCode("1");
        System.out.println(result);
        return result;
    }


    /**
     * 找回密码所发验证码，将验证码存到redis
     *
     * @return
     */
    @PostMapping("/forgetPassCode")
    Result forgetPassCode(@RequestBody Users user, HttpServletRequest request) throws Exception {

        HttpSession session = request.getSession();
        return userService.sendforgetCode(user.getUsername(), session);
    }

    /**
     * 找回密码时比较用户传入验证码是否一致
     *
     * @param isCode
     * @param request
     * @return
     */
    @PostMapping("/checkForgetCode")
    Result checkForgetCode(@RequestBody IsCode isCode, HttpServletRequest request) {

        return userService.checkForgetCode(isCode, request);
    }

    /**
     * 找回密码最后一步，设置密码
     *
     * @return
     */
    @PostMapping("/changeForgetPassword")
    Result changeForgetPassword(@RequestBody Users user, HttpServletRequest request) {

        return userService.changeForgetPassword(user, request);
    }

    /**
     * 修改个人信息
     *
     * @param userDTO
     * @return
     */
    @PostMapping("/changeUserInfo")
    DragonResult changeUserInfo(@RequestBody Users userDTO, HttpSession httpSession) {

        // 模拟 session
        //
        //httpSession.setAttribute("username","13187029351");
        // System.out.println(userDTO.toString());
        //String  username = (String) httpSession.getAttribut``e("username");
        //System.out.println(username);

        return userService.changeUserInfo(userDTO);
    }

    /**
     * 用户密码修改
     *
     * @return
     */
    @PostMapping("/changePassword")
    DragonResult changePassword(@RequestBody PasswordChange passwordChange, @RequestParam String username, HttpSession httpSession) {

        // 模拟 session
        //httpSession.setAttribute("username","13187029351");// System.out.println(userDTO.toString());
       // String  username = (String) httpSession.getAttribute("username");

        return userService.changePassword(passwordChange, username);
    }

    /**
     * 根据用户类型返回用户数量
     */
    @PostMapping("/getUserNum")
    ResultMap getUserNum(@RequestBody Users users) {
        String userType = users.getUserType();
        System.out.println(userType);
        if (userType.equals("司机") || userType.equals("审核员") || userType.equals("管理员")) {
            Integer num = userService.getUserNumByType(userType);
            Map<String, Object> map = new HashMap<>();
            map.put("userNum", num);
            return ResultMap.OK(map);
        } else {
            return ResultMap.NOK("请输入用户类型");
        }
    }

}
